﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Web;
using Google.Translates.Core.Entries;

namespace Google.Translates.Core
{
    public class TranslatorByGoogleHttp : TranslatorByGoogle
    {
        public TranslatorByGoogleHttp()
        {
            
        }

        public TranslatorByGoogleHttp(int appIdIndex)
        {
            
        }
        /// <summary>
        /// 把JsonString轉換成TranslateResult對象,并加上之前斷句時的標點符號
        /// </summary>
        /// <param name="jsonString"></param>
        /// <param name="splitKeyVals"></param>
        /// <returns></returns>
        public TranslationResult CreateTranslationResult(string jsonString, List<string> splitKeyVals)
        {
            var mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            var serializer = new DataContractJsonSerializer(typeof(TranslationResult));
            var transData = (TranslationResult)serializer.ReadObject(mStream);
            if (splitKeyVals != null && transData != null &&
                transData.Data != null && transData.Data.Translations != null
                && splitKeyVals.Count <= transData.Data.Translations.Length)
            {
                for (int i = 0; i < splitKeyVals.Count; i++)
                {
                    string transVal = transData.Data.Translations[i].TranslatedText;

                    int tempIndex = transVal.LastIndexOfAny(StringHelper.GetSentencesSplitsKey());
                    if (tempIndex > -1 && tempIndex + 1 == transVal.Length)
                        transVal = transVal.Remove(transVal.Length - 1);
                    transData.Data.Translations[i].TranslatedText = transVal + splitKeyVals[i];
                }
            }
            return transData;
        }

        public object CreateJsonResult(string jsonString, Type jsonType)
        {
            var mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            var serializer = new DataContractJsonSerializer(jsonType);
            var returnValue = serializer.ReadObject(mStream);
            return returnValue;
        }

        public DetectionResult CreateDetectionResult(string jsonString)
        {
            return (DetectionResult)CreateJsonResult(jsonString, typeof(DetectionResult));
        }

        public LanguageResult CreateLanguageResult(string jsonString)
        {
            return (LanguageResult)CreateJsonResult(jsonString, typeof(LanguageResult));
        }

        public override object GetTranslations(List<string> shotSentence, string srcLangKey, string trgLangKey)
        {
            var sbUrl = new StringBuilder("https://www.googleapis.com/language/translate/v2?key=" + m_AppId);
            if (!string.IsNullOrEmpty(srcLangKey))
                sbUrl.Append("&source=" + srcLangKey);
            sbUrl.Append("&target=" + trgLangKey);
            foreach (string strSource in shotSentence)
            {
                var val = strSource;
                if(!string.IsNullOrEmpty(val))
                    sbUrl.Append("&q=" + HttpUtility.UrlEncode(val));
            }
            var strTrans = m_HttpHlp.GetResultStringByRequestPostForGoogle(sbUrl.ToString());
            return CreateTranslationResult(HttpUtility.HtmlDecode(strTrans), null);
        }
     
        //https://www.googleapis.com/language/translate/v2/detect?key=INSERT-YOUR-KEY&q=google+translate+is+fast
        public string DetectTheSentence(string sentenceVal)
        {
            var reVal = "";
            var sbUrl = new StringBuilder("https://www.googleapis.com/language/translate/v2/detect?key=" + m_AppId);
            sbUrl.Append("&q=" + HttpUtility.UrlEncode(sentenceVal));
            var detectInfo = m_HttpHlp.GetResultStringByRequestPostForGoogle(sbUrl.ToString());
            var objDetect = CreateDetectionResult(HttpUtility.HtmlDecode(detectInfo));
            if (objDetect != null && objDetect.Data != null && objDetect.Data.Detections != null
                && objDetect.Data.Detections.Length > 0) reVal = objDetect.Data.Detections[0][0].Language;
            return reVal;
        }

        //https://www.googleapis.com/language/translate/v2/languages?key=INSERT-YOUR-KEY&target=zh-TW
        public LanguageResult GetLanguageInfos(string trgLangKey)
        {
            var sbUrl = new StringBuilder("https://www.googleapis.com/language/translate/v2/languages?key=" + m_AppId);
            if (!string.IsNullOrEmpty(trgLangKey))
                sbUrl.Append("&target=" + trgLangKey);
            var langInfo = m_HttpHlp.GetResultStringByRequestPostForGoogle(sbUrl.ToString());
            return CreateLanguageResult(HttpUtility.HtmlDecode(langInfo));
        }
    }
}
